package controller
{
	import away3d.animators.SkeletonAnimator;
	import away3d.animators.transitions.CrossfadeTransition;
	import away3d.entities.Mesh;
	import away3d.materials.ColorMaterial;
	import away3d.primitives.CubeGeometry;
	
	import flash.display.BitmapData;
	import flash.geom.Vector3D;
	import flash.utils.setTimeout;
	
	import gameObject.Enemy;
	import gameObject.GameObjectBase;
	import gameObject.resources3D.EnemyResource;
	
	import tool.tweener.Tweener;

	public class EnemyController extends GameControllerBase
	{
		private var _enemy:Enemy;
		private var _enemyRes:EnemyResource;
		
		private var _startOffset:Vector3D;
		private var _zeroPos:Vector3D;
		
		private var _restTimeOut:int;
		
		private var animator:SkeletonAnimator;
		private var transition:CrossfadeTransition = new CrossfadeTransition(0.2);
		
		public function EnemyController(startOffset:Vector3D)
		{
			_startOffset = startOffset;
		}
		
		override public function setup(target:GameObjectBase):void
		{
			super.setup(target);
			
			_enemy = target as Enemy;
			_enemyRes = _enemy.resource as EnemyResource;
			
			transition.blendSpeed = 0.5/_enemy.mspd;
			
			_zeroPos = _enemy.position;
			
			animator = _enemyRes.mesh.animator as SkeletonAnimator;
			
			_enemy.position = _enemy.position.add(_startOffset);
			
			var angle:Number = Math.atan2(_startOffset.z, -_startOffset.x);
			angle = angle*180/Math.PI-90;
			
			_enemy.rotationY = angle;
			
			animator.play("wait");
		}
		
		public function start():void
		{
			animator.play("walk");
			
			var time:Number = _startOffset.length/_enemy.mspd;
			time *=  1/60;
			
			Tweener.addTween(_enemy,
				{
					x:_zeroPos.x,
					y:_zeroPos.y,
					z:_zeroPos.z,
					time:time,
					onComplete:startSeek,
					transition:"linear"
				});
		}
		
		/**
		 *去下一个巡逻点 
		 */		
		private function startSeek():void
		{
			var isRest:Number = Math.random()*100;
			if(isRest>30)
			{
				var gotRightPlace:Boolean = false;
				var newPlace:Object;
				var maxCount:uint = 0;
				
				while(!gotRightPlace)
				{
					maxCount++;
					newPlace = seekNewPlace();
					//gotRightPlace = true;
					if(Math.abs(newPlace.turnAng)<90 && newPlace.dis > 50)gotRightPlace = true;
					if(maxCount>10)gotRightPlace = true;
				}
				
				if(animator.activeAnimationName=="wait")
				{
					animator.play("walk",transition);
				}
				
				var turnTime:Number = Math.abs(newPlace.turnAng/100);
				if(Math.abs(newPlace.turnAng)<40)turnTime*=4;
				Tweener.addTween(_enemy,
				{
					rotationY:newPlace.angle,
					time:turnTime,
					transition:"easeinoutsine"
				});
				
				var tranType:String = "linear"
				if(Math.abs(newPlace.turnAng)>60)tranType = "easeinsine"
				Tweener.addTween(_enemy,
				{
					x:newPlace.tarX,
					z:newPlace.tarY,
					time:newPlace.time,
					onComplete:startSeek,
					transition:tranType
				});
				
			}else rest();
		}
		
		/**
		 * 生成下一下巡逻点的坐标
		 */		
		private function seekNewPlace():Object
		{
			var result:Object = new Object;
			
			var pos:Object;
			var gotPos:Boolean = false;
			while(!gotPos)
			{
				pos = radPos();
				var px:Number = CollisionWorld.mapScaleX*(CollisionWorld.hitStartX+pos.x);
				var py:Number = CollisionWorld.mapScaleY*(CollisionWorld.hitStartX-pos.y);
				
				if(buildingHitTest(px,py) == false)gotPos=true;
			}
			
			var tarX:Number = pos.x;
			var tarY:Number = pos.y;
			
			var dx:Number = tarX - _enemy.x;
			var dy:Number = _enemy.z - tarY;
			var dis:Number = Math.sqrt(dx*dx + dy*dy);
			var angle:Number = Math.atan2(dy, dx);
			
			var len:Number = 10;//每隔多远检查一次路径碰撞
			
			var count:int = dis/len;
			for(var i:uint=1;i<count;i++)//检查在前进的路径中是否会进入碰撞区域，如果是，则将首次碰撞的坐标减去自己的半径作为目标点输出
			{
				var cx:Number = _enemy.x + Math.cos(angle)*i*len;
				var cy:Number = _enemy.z - Math.sin(angle)*i*len;	
				
				px = CollisionWorld.mapScaleX*(CollisionWorld.hitStartX+cx);
				py = CollisionWorld.mapScaleY*(CollisionWorld.hitStartY-cy);
				
				if(buildingHitTest(px,py) == true)
				{
					tarX = cx-Math.cos(angle)*4*_enemy.radius;
					tarY = cy+Math.sin(angle)*4*_enemy.radius;
					
					dx = tarX - _enemy.x;
					dy = _enemy.z - tarY;
					dis = Math.sqrt(dx*dx + dy*dy);
					
					break;
				}
			}
			
			angle = angle*180/Math.PI-90;
			var turnAng:Number =_enemy.rotationY -  angle;
			
			//当转身的角度超过180度时，则反转一次转身角度，好让角色转身时的角度始终小于180度
			if(turnAng>180)
			{
				angle+=360;
				turnAng =Math.abs(_enemy.rotationY -  angle);
			}else if(turnAng<-180)
			{
				angle-=360;
				turnAng =Math.abs(_enemy.rotationY -  angle);
			}
			
			/////////////////////////////////////////
			var time:Number = dis/_enemy.mspd;
			time *=  1/60;
			
			result.tarX = tarX;
			result.tarY = tarY;
			result.dis = dis;
			result.angle = angle;
			result.turnAng = turnAng;
			result.time = time;
			
			return result;
		}
		
		/**
		 * 在怪物的巡逻范围内随机生成一个坐标
		 */
		private function radPos():Object
		{
			var pos:Object = new Object;
			
			var tarX:Number = _zeroPos.x + Math.random()*_enemy.mran - 0.5*_enemy.mran;
			var tarY:Number = _zeroPos.z + Math.random()*_enemy.mran - 0.5*_enemy.mran;
			
			pos.x = tarX;
			pos.y = tarY;
			
			return pos;
		}
		
		/**
		 * 检查一个坐标点是否在碰撞区域内
		 */		
		private function buildingHitTest(X:Number,Y:Number):Boolean
		{
			var mapData:BitmapData = CollisionWorld.collisionMap.bitmapData;
			var p:uint = mapData.getPixel(X,Y);
			
			if(p>0)return true
			else return false;
		}
		
		private function rest():void
		{
			animator.play("wait",transition);
			
			var restTime:Number = Math.random()*4;
			_restTimeOut = setTimeout(startSeek,restTime*1000);
			
			//Global.gc();
		}
		
		
		
		
		
	}
}